from selenium.webdriver.common.by import By

from . import navigate


def get_movie_list(browser):
    navigate.wait_for_ajax(browser)

    elements_list = browser.find_element_by_id('results').find_elements_by_tag_name("a")
    return [name.find_element(By.CLASS_NAME, 'title').text for name in elements_list]


def get_movie_name(browser):
    movie_list = get_movie_list(browser)

    if len(movie_list) != 0:
        return movie_list.pop()

    movie_name = 'movie_1'
    movie_year = '2001'

    navigate.goto_main_page(False)
    browser.find_element_by_xpath(".//a/img[@title='Add movie']").click()
    browser.find_element_by_name('name').send_keys(movie_name)
    browser.find_element_by_name('year').send_keys(movie_year)
    browser.find_element_by_xpath(".//a/img[@title='Save']").click()
    navigate.goto_main_page(False)

    return movie_name

